package com.xiyoukt.springboot.handler;

import com.xiyoukt.springboot.Result;
import com.xiyoukt.springboot.exception.BusinessException;
import com.xiyoukt.springboot.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

// 创建统一处理类
//@RestControllerAdvice
//@ControllerAdvice
public class GobalExceptionHandler {

    private Logger log = LoggerFactory.getLogger(GobalExceptionHandler.class);

    // 用来进行全局的异常处理，可以指定捕获哪些异常，包括继承自他的异常
    @ExceptionHandler({Exception.class})
    public Result<Boolean> exceptionHandler(HttpServletRequest request, Exception e){
        log.error("error", e);
        ResultUtil<Boolean> resultUtil = new ResultUtil<>();
        if(e instanceof BusinessException){
            BusinessException businessException = (BusinessException) e;
            return resultUtil.fail(businessException.getCode(), businessException.getMessage());
        }
        return resultUtil.fail(500, "发生未知异常");
    }

}
